package com.entrogy.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.entrogy.bean.*;
import com.entrogy.service.CourseSystemService;
import com.entrogy.service.UtilsService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName DemoDataListener
 * @Description
 * @Author luoxingjiang
 * @Date 2020-03-20 上午 9:45
 * @Version 1.0
 **/
public class ImportCourseListener extends AnalysisEventListener<ImportCourseEntity> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportCourseListener.class);

    private CourseSystemService courseSystemService;

    private UtilsService utilsService;

    private RestTemplate restTemplate;

    List<ImportCourseEntity> failImportCourseList = new ArrayList<>();

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;

    List<ImportCourseEntity> list = new ArrayList<>();

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *  @param courseSystemService
     * @param utilsService
     * @param restTemplate
     */
    public ImportCourseListener(CourseSystemService courseSystemService, UtilsService utilsService, RestTemplate restTemplate) {
        this.courseSystemService = courseSystemService;
        this.utilsService = utilsService;
        this.restTemplate = restTemplate;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ImportCourseEntity data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        list.forEach(importCourseEntity -> {
            CourseSystemCourseEntity courseEntity = new CourseSystemCourseEntity();
            courseEntity.setCourseName(importCourseEntity.getCourseName()).setCourseImage("")
            .setCourseDesc(importCourseEntity.getCourseDesc()).setDeadline(new Date()).setCourseLimitCount(importCourseEntity.getCourseLimitCount())
            .setWeekNumber(importCourseEntity.getWeekNumber()).setCourseCount(importCourseEntity.getCourseCount()).setEnableStatus(0)
            .setOperateUserId("11571797615086").setSchoolCode(510182006);
            // 解析教师安排数据
            List<CourseSystemCourseArrangeEntity> courseSystemCourseArrangeList = new ArrayList<>();
            if (StringUtils.isNoneBlank(importCourseEntity.getTeacherName())){
                String[] teacherNameList = importCourseEntity.getTeacherName().split("、");
                for (String teacherName : teacherNameList) {
                    CourseSystemCourseArrangeEntity courseSystemCourse = new CourseSystemCourseArrangeEntity();
                    List<UserEntity> teacherList = utilsService.listSchoolTeacher(510182006, null, null, null, teacherName);
                    if (teacherList.size() != 1){
                        LOGGER.error("导入课程：{}时，教师：{}名字重复或不存在，该课程未进行导入！", importCourseEntity, teacherName);
                        failImportCourseList.add(importCourseEntity);
                        return;
                    }
                    UserEntity teacher = teacherList.get(0);
                    courseEntity.setCreateUserId(teacher.getId());
                    courseSystemCourse.setTeacherId(teacher.getId()).setTeacherPhoto(teacher.getPhoto()).setTeacherName(teacherName);
                    courseSystemCourseArrangeList.add(courseSystemCourse);
                }
            }else {
                LOGGER.error("导入课程：{}时，教师：{}名字不存在，该课程未进行导入！", importCourseEntity, importCourseEntity.getTeacherName());
                failImportCourseList.add(importCourseEntity);
                return;
            }
            courseEntity.setCourseArrangeList(courseSystemCourseArrangeList);
            // 解析课程上课时间数据
            List<CourseSystemCourseTimeEntity> courseTimeList = new ArrayList<>();
            if (importCourseEntity.getCourseTimeWeek1() != null){
                if (importCourseEntity.getCourseTimeWeek1() == 3){
                    CourseSystemCourseTimeEntity courseTime = new CourseSystemCourseTimeEntity();
                    courseTime.setDayOfWeek(3).setCreateUserId("11571797615086");
                    List<Integer> courseOrderList = new ArrayList<>();
                    courseOrderList.add(9);
                    courseTime.setCourseOrderList(courseOrderList);
                    courseTimeList.add(courseTime);
                }
            }
            if (importCourseEntity.getCourseTimeWeek2() != null){
                if (importCourseEntity.getCourseTimeWeek2() == 4){
                    CourseSystemCourseTimeEntity courseTime = new CourseSystemCourseTimeEntity();
                    courseTime.setDayOfWeek(4).setCreateUserId("11571797615086");
                    List<Integer> courseOrderList = new ArrayList<>();
                    courseOrderList.add(9);
                    courseTime.setCourseOrderList(courseOrderList);
                    courseTimeList.add(courseTime);
                }
            }
            courseEntity.setCourseTimeList(courseTimeList);
            // 解析课程限制数据，注意limitGradeId为1代表初中都能报名，2代表高中都能报名
            List<CourseSystemCourseLimitEntity> courseLimitList = new ArrayList<>();
            if (importCourseEntity.getLimitGrade() != null){

                if (importCourseEntity.getLimitGrade() == 1){
                    CourseSystemCourseLimitEntity courseLimit = new CourseSystemCourseLimitEntity();
                    courseLimit.setLimitGradeId(1220000);
                    courseLimitList.add(courseLimit);
                    CourseSystemCourseLimitEntity courseLimit1 = new CourseSystemCourseLimitEntity();
                    courseLimit1.setLimitGradeId(1210000);
                    courseLimitList.add(courseLimit1);
                    CourseSystemCourseLimitEntity courseLimit2 = new CourseSystemCourseLimitEntity();
                    courseLimit2.setLimitGradeId(1200000);
                    courseLimitList.add(courseLimit2);
                }else if (importCourseEntity.getLimitGrade() == 2){
                    CourseSystemCourseLimitEntity courseLimit = new CourseSystemCourseLimitEntity();
                    courseLimit.setLimitGradeId(1100000);
                    courseLimitList.add(courseLimit);
                    CourseSystemCourseLimitEntity courseLimit1 = new CourseSystemCourseLimitEntity();
                    courseLimit1.setLimitGradeId(1110000);
                    courseLimitList.add(courseLimit1);
                    CourseSystemCourseLimitEntity courseLimit2 = new CourseSystemCourseLimitEntity();
                    courseLimit2.setLimitGradeId(1120000);
                    courseLimitList.add(courseLimit2);
                }else {
                    CourseSystemCourseLimitEntity courseLimit = new CourseSystemCourseLimitEntity();
                    courseLimit.setLimitGradeId(importCourseEntity.getLimitGrade());
                    courseLimitList.add(courseLimit);
                }
            }
            courseEntity.setCourseLimitList(courseLimitList);
//            HttpHeaders headers = new HttpHeaders();
//            MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
//            headers.setContentType(type);
//            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//            JSONObject jsonObj = JSONObject.fromObject(courseEntity);
//            HttpEntity<String> formEntity = new HttpEntity<>(jsonObj.toString(), headers);
            int i = 0;
            while (i < 5){
                try {
                    i++;
                    CourseSystemCourseEntity courseEntity1 = restTemplate.postForObject("http://schoolyard.face2id.com/course-system/course-add", courseEntity, CourseSystemCourseEntity.class);
                    break;
                } catch (RestClientException e) {
                    if (i == 5){
                        LOGGER.error("重试达到5次，程序退出！");
                        return;
                    }
                    LOGGER.info("正在进行第{}次重试！",i + 1);
                }
            }

        });
        LOGGER.info("存储数据库成功！");
    }

    public List<ImportCourseEntity> getFailImportCourseList() {
        return failImportCourseList;
    }

    public void setFailImportCourseList(List<ImportCourseEntity> failImportCourseList) {
        this.failImportCourseList = failImportCourseList;
    }


}
